package com.ylsoft.android.facerepeater.net.thrift.server.transaction;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.ruoyi.faceApi.click.FaceCallBack;
import org.apache.thrift.TProcessor;
import org.apache.thrift.TProcessorFactory;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.server.TThreadedSelectorServer;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TNonblockingServerSocket;
import org.apache.thrift.transport.TNonblockingServerTransport;


/**
 * @author wwy
 */
public class DoorControlServer {
	public static  FaceCallBack faceCallBack = new FaceCallBack();
	public static final String SERVER_PORT = "9999";
	// 参数初始化8877
	private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
	// 核心线程数量大小
	private static final int corePoolSize = Math.max(2, Math.min(CPU_COUNT - 1, 4));
	public static void startServer() {
		int port = 9999;
		if (SERVER_PORT != null) {
			port = Integer.parseInt(SERVER_PORT);
		}
		try {
			System.out.println("DoorControlServer TThreadPoolServer start ....");
			// 非阻塞式的，配合TFramedTransport使用
			TNonblockingServerTransport serverTransport = new TNonblockingServerSocket(port);
			// 关联处理器与Service服务的实现
			TProcessor processor = new AccessThriftService.Processor<AccessThriftService.Iface>(faceCallBack);
			// 目前Thrift提供的最高级的模式，可并发处理客户端请求
			TThreadedSelectorServer.Args args = new TThreadedSelectorServer.Args(serverTransport);
			args.processor(processor);
			// 设置协议
			args.protocolFactory(new TBinaryProtocol.Factory());
			// 设置传输工厂，使用非阻塞方式，按块的大小进行传输，类似于Java中的NIO
			args.transportFactory(new TFramedTransport.Factory());
			// 设置处理器工厂,只返回一个单例实例
			args.processorFactory(new TProcessorFactory(processor));
			// 多个线程，主要负责客户端的IO处理
			args.selectorThreads(CPU_COUNT);
			// 工作线程池
			ExecutorService pool = Executors.newFixedThreadPool(corePoolSize);
			args.executorService(pool);
			TThreadedSelectorServer server = new TThreadedSelectorServer(args);
			System.out.println("DoorControlServer on port ：" + port + "......");
			server.serve();
		} catch (Exception e) {
			System.out.println("DoorControlServer start error!!!");
			e.printStackTrace();
		}
	}

}
